package com.briup.srms.project.web.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.briup.srms.project.bean.Project;
import com.briup.srms.project.bean.extend.ProjectExtend;
import com.briup.srms.project.service.IProjectService;
import com.jacky.base.utils.ExcelUtils;
import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.jacky.base.utils.PageVM;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: 杰普学生管理系统
 * @description: 毕业设计项目的控制器类
 * @author: charles
 * @create: 2021-1-14 11:09
 **/
@Api(description="毕业设计项目相关接口")
@Validated
@RestController
@RequestMapping("/project/project")
public class ProjectController {
	
	@Autowired
	private IProjectService projectService;
	
	
	@ApiOperation(value = "分页多条件获取毕业设计信息")
	@GetMapping("pageQuery")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"), 
		@ApiImplicitParam(name = "name", value = "毕业设计名称", paramType = "query"), 
		@ApiImplicitParam(name = "directionId", value = "方向编号", paramType = "query"), 
	})
	public Message pageQuery(int page, int pageSize,String name,Long directionId) {
		PageVM<Project> pageVM = projectService.pageQuery(page, pageSize, name,directionId);
		return MessageUtil.success(pageVM);
	}
	
	@ApiOperation(value = "分页多条件获取毕业设计信息",notes="级联了所属方向数据")
	@GetMapping("pageQueryCascade")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页大小", required = true, paramType = "query"), 
		@ApiImplicitParam(name = "name", value = "毕业设计名称", paramType = "query"), 
		@ApiImplicitParam(name = "directionId", value = "方向编号", paramType = "query"), 
	})
	public Message pageQueryCascade(int page, int pageSize,String name,Long directionId) {
		PageVM<ProjectExtend> pageVM = projectService.pageQueryCascade(page, pageSize, name,directionId);
		return MessageUtil.success(pageVM);
	}
	
	@ApiOperation(value = "保存或者更新毕业设计信息")
	@PostMapping("saveOrUpdate")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "name", value = "毕业设计名称", required = true, paramType = "query"),
		@ApiImplicitParam(name = "introduce", value = "毕业设计功能描述", required = true, paramType = "query")
	})
	public Message saveOrUpdate(Project project) {
		projectService.saveOrUpdate(project);
		return MessageUtil.success("更新成功！");
	}
	
	@ApiOperation(value = "删除毕业设计信息")
	@GetMapping("deleteById")
	@ApiImplicitParams({ 
		@ApiImplicitParam(name = "id", value = "毕业设计编号", required = true, paramType = "query"),
	})
	public Message deleteById(long id) {
		projectService.deleteById(id);
		return MessageUtil.success("删除成功！");
	}
	
	@ApiOperation(value = "下载批量导入模板", produces = "application/octet-stream")
	@GetMapping("downloadTemplate")
	public void downloadTemplate(HttpServletResponse response) throws Exception {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = this.getClass().getResourceAsStream("/template/project_template.xlsx");
			outputStream = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("批量导入毕业设计题目模板.xlsx", "utf-8"));
			IOUtils.copy(inputStream, outputStream);
			response.flushBuffer();
		} finally {
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream !=null) {
				outputStream.close();
			}
		}
	}

	
	@ApiOperation(value = "批量导入毕业设计题目数据")
	@PostMapping("uploadProjects")
	public Message uploadOldStudent(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws Exception {
		File toFile = null;
		if (file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		// 解析数据
		List<List<Object>> list = ExcelUtils.readExcel(toFile);
		List<Project> projects = new ArrayList<>();
		for (List<Object> props : list) {
			Project project = new Project();
			// 设置基本信息
			for (int i=0;i<props.size();i++) {
				Object prop = props.get(i);
				switch (i) {
				case 0:	// 毕业设计题目
					project.setName(prop+"");
					break;
				case 1:	// 毕业设计功能介绍
					project.setIntroduce(prop+"");
					break;
				case 2:	// 难度
					project.setLevel(prop+"");
					break;
				case 3:	// 所属方向
					project.setDirectionName(prop+"");
					break;
				default:
					break;
				}
			}
			projects.add(project);
		}
		projectService.batchInsert(projects);
		// 调用业务逻辑层代码完成批量保存操作
		return MessageUtil.success("导入成功");
	}
	
	public void inputStreamToFile(java.io.InputStream ins, File file) {
		try {
			java.io.OutputStream os = new java.io.FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
